package com.pagoda.nerp.trade.common.component.realm;

import com.pagoda.nerp.trade.entity.MdAccount;
import com.pagoda.nerp.trade.service.MdAccountService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Jungle on 2017/1/4.
 */
//@Component
public class H5JDBCRealm extends JdbcRealm{

    private static Logger logger = LoggerFactory.getLogger(H5JDBCRealm.class);

    @Autowired
    private MdAccountService mdAccountService;

    /**
     * 重写登录认证，将权限认证下放到业务自身DB
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = String.valueOf(usernamePasswordToken.getUsername());
        
        // 获取DB中username的信息
        MdAccount mdAccount = mdAccountService.selectByAccount(username);
        AuthenticationInfo authenticationInfo = null;
        if (null != mdAccount) {
            logger.info("H5JDBCRealm -> 当前账号{}登录鉴权获取用户成功!",username);
            String openid = new String(usernamePasswordToken.getPassword());
            if (openid.equals(mdAccount.getOpenid())) {
                authenticationInfo = new SimpleAuthenticationInfo(mdAccount.getAccount(),mdAccount.getOpenid(), getName());
            }
        }
        Subject subject = SecurityUtils.getSubject();
		subject.getSession().setAttribute("mdAccount", mdAccount);
        return authenticationInfo;

    }

}
